import axios from "axios";
import { Loading, Notification } from "element-ui";
import router from "../../router";
let loadingInstance;
// http请求拦截器
axios.interceptors.request.use(
  config => {
    let token = sessionStorage.getItem("vf");
    if (token) {
      config.headers["vf"] = token;
    }
    return config;
  },
  error => {
    return Promise.reject(error);
  }
);
// http响应拦截器
axios.interceptors.response.use(
  data => {
    loadingInstance && loadingInstance.close();
    if (data.data.code === 0) {
      Notification({
        title: data.data.code === 1 ? "成功" : "失败",
        message: data.data.msg,
        type: data.data.code === 1 ? "success" : "error",
        duration: 2000
      });
    }
    if (data.data.data && data.data.data.token) {
      sessionStorage.setItem("vf", data.data.data.token);
    }
    return data.data;
  },
  error => {
    if (error.response) {
      Notification({
        title: "失败",
        message: error.response.data.msg || error.message,
        type: "error",
        duration: 2000
      });
      if (error.response.status === 403 || error.response.status === 401) {
        sessionStorage.clear();
        router.push("/login");
      }
    }
    return Promise.reject(error);
  }
);

axios.defaults.withCredentials = false;

export default class Base {
  //获取
  get(url, loading = false, config = {}) {
    if (loading) {
      loadingInstance = Loading.service({
        fullscreen: true,
        background: "rgba(0, 0, 0, .7)"
      });
    }
    return axios.get(url, config).catch(err => {
      console.error(err.message || err);
    });
  }
  //新增
  post(url, data, loading = false, config = {}) {
    if (loading) {
      loadingInstance = Loading.service({
        fullscreen: true,
        background: "rgba(0, 0, 0, .7)"
      });
    }
    return axios.post(url, data, config);
  }
  //修改
  put(url, data, loading = false, config = {}) {
    if (loading) {
      loadingInstance = Loading.service({
        fullscreen: true,
        background: "rgba(0, 0, 0, .7)"
      });
    }
    return axios.put(url, data, config);
  }
  //删除
  delete(url, loading = false, config = {}) {
    if (loading) {
      loadingInstance = Loading.service({
        fullscreen: true,
        background: "rgba(0, 0, 0, .7)"
      });
    }
    return axios.delete(url, config);
  }
  //上传
  upload(url, data) {
    return axios.post(url, data, {
      headers: { "Content-Type": "multipart/form-data" }
    });
  }

  notify(code, msg) {
    Notification({
      title: code === 1 ? "成功" : "失败",
      message: msg,
      type: code === 1 ? "success" : "error",
      duration: 2000
    });
  }
}
